package com.mezz.bones.framework.gateway.filter;

import com.mezz.bones.framework.gateway.constant.GatewayConstants;
import com.mezz.bones.framework.gateway.resolver.RouteVersionResolver;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
@AllArgsConstructor
public class RouteVersionHeaderFilter implements GlobalFilter, Ordered {

    private final RouteVersionResolver routeVersionResolver;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String routeVersion = routeVersionResolver.resolve(exchange);
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(GatewayConstants.X_ROUTE_VERSION_HEADER_KEY, routeVersion)
                .build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return -100;
    }
}